<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class SMB_Controller extends CI_Controller {
	private $segment;
	protected $userinfo;
	protected $navigation;
	
	public function __construct() {
		parent::__construct();
		$this->_get_userinfo();
		$this->segment = $this->uri->segment(1);
		if ($this->userinfo === NULL) {
			if ($this->segment != 'home' && $this->segment !== FALSE) {
				$this->_goto_home();
			}
		} else {
			if ($this->segment != $this->userinfo['role'] && $this->segment != 'home'
					&& $this->segment !== FALSE) {
				$this->_goto_home();
			}
		}
	}
	
	protected function _get_userinfo($reset = TRUE) {
		$this->userinfo = $this->authentication->get_current_user();
		$this->navigation = get_navigation($this->userinfo);
		if ($reset == TRUE) {
			$this->_reset_userdata();
		}
	}
	
	protected function _reset_userdata() {
		$this->session->unset_userdata('studentcheck');
	}
	
	protected function _goto_home() {
		if ($this->userinfo === NULL) {
			redirect('home/index', 'refresh');
		} else {
			switch ($this->userinfo['role']) {
				case ROLE_MAHALUM:
					redirect('mahalum/home/index', 'refresh');
					break;
				case ROLE_MAHASISWA:
					redirect('mahasiswa/home/index', 'refresh');
					break;
				case ROLE_SPONSOR:
					redirect('sponsor/home/index', 'refresh');
					break;
				case ROLE_ADKESMA:
					redirect('adkesma/home/index', 'refresh');
					break;
				default:
					redirect('home/index', 'refresh');
					break;
			}
		}
	}
	
	protected function _goto_userpage() {
		if ($this->userinfo === NULL) {
			// do nothing
		} else {
			$this->_goto_home();
		}
	}
	
	protected function _load_common_header($script = NULL) {
		if ($script == NULL) {
			$this->load->view('common/header');
		} else {
			$this->load->view('common/header', array('script' => $script));
		}	
	}
	
	protected function _load_common_navigation() {
		$this->load->view('common/navigation', array('userinfo' => $this->userinfo, 'anchors' => $this->navigation));
	}
	
	protected function _load_common_sidebar($anchors) {
		$this->load->view('common/sidebar', array('anchors' => $anchors));
	}
	
	protected function _load_common_footer() {
		$this->load->view('common/footer');
	}
	
	protected function _validate_offset($offset, $max, $redirect) {
		if ($offset == FALSE) {
			return 0;
		} else if (!ctype_digit($offset)) {
			redirect($redirect, 'location');
			exit;
		} else if (intval($max) == 0 && intval($offset) != 0) {
			redirect($redirect, 'location');
			exit;
		} else if (intval($max) == 0) {
			return 0;
		} else if (intval($offset) >= intval($max) || intval($offset) < 0) {
			redirect($redirect, 'location');
			exit;
		} else {
			return $offset;
		}
		return 0;
	}
}
